#!/usr/bin/env python
# -*- coding: utf-8 -*-

import rtp_datagram
import rfc2435jpeg

from twisted.internet.protocol import DatagramProtocol
from config import config

class RTP_MJPEG_Client(DatagramProtocol):
    def __init__(self, Camproxy_Process, im_id):
        conf = config()
        self.Process = Camproxy_Process
        self.id = im_id
        self.i = 0
        self.skip_frames = conf.cameras[im_id]['skip_frames']
        self.prevSeq = -1
        self.lost_packet = 0
        self.jpeg = rfc2435jpeg.RFC2435JPEG()

        def datagramReceived(self, datagram, address):
        rtp_dg = rtp_datagram.RTPDatagram()
        rtp_dg.Datagram = datagram
        rtp_dg.parse()
        if self.prevSeq != -1:
            if (rtp_dg.SequenceNumber != self.prevSeq + 1) and rtp_dg.SequenceNumber != 0:
                self.lost_packet = 1
        self.prevSeq = rtp_dg.SequenceNumber
        if rtp_dg.PayloadType == 26: #JPEG compressed video
            if self.i == self.skip_frames:
                self.jpeg.Datagram = rtp_dg.Payload
                self.jpeg.parse()
            if rtp_dg.Marker:
                if not self.lost_packet:
                    if self.i == self.skip_frames:
                        self.jpeg.makeJpeg()
                        self.Process.processImage(self.jpeg.JpegImage, self.id)
                        self.i = 0
                    else:
                        self.i += 1
                else:
                    #print "RTP packet lost"
                    self.lost_packet = 0
                    self.jpeg.JpegPayload = ""
